// pages/cart/cart.js
const CartHttp = require("../../utils/CartHttp");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        carts: [],
        allChecked: "",
        sum: null
    },

    onLoad: async function (options) {
        var res = await CartHttp.getCart();
        res.data.results.forEach(item => {
            item.count = item.count.num
        })
        var allChecked = res.data.results.every(item => {
            return item.checked;
        })
        this.setData({
            carts: res.data.results,
            allChecked
        })
        this.handleSum();
    },
    onChange(e) {
        var carts = this.data.carts;
        var { aid } = e.currentTarget.dataset;
        carts.forEach(item => {
            if (item.id == aid) {
                item.checked = e.detail
            }
        })
        var allChecked = carts.every(item => {
            return item.checked;
        })
        this.handleSum();
        this.setData({
            carts,
            allChecked
        })
    },
    onAllChange(e) {
        var carts = this.data.carts;
        carts.forEach(item => {
            item.checked = e.detail
        })
        this.handleSum();
        this.setData({
            carts,
            allChecked: e.detail
        })
    },
    handleNum(e) {
        var carts = this.data.carts;
        var { aid } = e.currentTarget.dataset;
        carts.forEach(item => {
            if (item.id == aid) {
                item.count = e.detail
            }
        })
        this.handleSum();
        this.setData({
            carts
        })
    },
    handleSum() {
        var sum = 0;
        var carts = this.data.carts;
        carts.forEach(item => {
            if (item.checked) {
                sum += item.count * item.price
            }
        })
        this.setData({
            sum
        })
    }
})